package com.wu.common.utils;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

/**
 * JSON 工具类
 *
 * @author wzd
 */
public class JsonUtils {
    private static final ObjectMapper objectMapper = new ObjectMapper();

    public static String toJsonString(Object object) {
        try {
            return objectMapper.writeValueAsString(object);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> T parseObject(String text, Class<T> clazz) {
        if (StrUtil.isEmpty(text)) {
            return null;
        }
        try {
            return objectMapper.readValue(text, clazz);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> T parseObject(byte[] bytes, Class<T> clazz) {
        if (ArrayUtil.isEmpty(bytes)) {
            return null;
        }
        try {
            return objectMapper.readValue(bytes, clazz);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> T parseObject(String text, TypeReference<T> typeReference) {
        try {
            return objectMapper.readValue(text, typeReference);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> List<T> parseArray(String text, Class<T> clazz) {
        if (StrUtil.isEmpty(text)) {
            return new ArrayList<>();
        }
        try {
            return objectMapper.readValue(text, objectMapper.getTypeFactory().constructCollectionType(List.class, clazz));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static String subString(String text, int length, String endWith) {
        if (StringUtils.isEmpty(text)) {
            return "";
        } else {
            int textLength = text.length();
            int byteLength = 0;
            StringBuffer returnStr = new StringBuffer();

            for(int i = 0; i < textLength && byteLength < length * 2; ++i) {
                String str_i = text.substring(i, i + 1);
                if (str_i.getBytes().length == 1) {
                    ++byteLength;
                } else {
                    byteLength += 2;
                }

                returnStr.append(str_i);
            }

            try {
                if (byteLength < text.getBytes("GBK").length) {
                    returnStr.append(endWith);
                }
            } catch (UnsupportedEncodingException var8) {
                var8.printStackTrace();
            }

            return returnStr.toString();
        }
    }

}
